package com.ziroom.crm.mq.rabbit.spring.support;

import com.ziroom.crm.mq.core.support.ProcessorInvokerDelegate;
import com.ziroom.crm.mq.core.support.SimpleProcessorInvokerDelegate;
import com.ziroom.crm.mq.rabbit.spring.core.ReliableRabbitListenerContainerFactory;
import com.ziroom.crm.mq.rabbit.spring.core.ReliableRabbitTemplate;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitListenerAnnotationBeanPostProcessor;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.retry.support.RetryTemplate;

/**
 * @author niXueChao
 * @date 2019/7/10
 */
@EnableRabbit
@SuppressWarnings("ALL")
public class ReliableRabbitAutoConfig {

    /**
     * 超时时间
     */
    private static final int TIMEOUT = 3000;

    @Bean
    public ReliableRabbitTemplate reliableRabbitTemplate(ConnectionFactory connectionFactory, @Autowired(required = false) RetryTemplate retryTemplate) {
        ReliableRabbitTemplate template = new ReliableRabbitTemplate();
        template.setConnectionFactory(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        // template.setMandatory(true);
        return template;
    }

    @Bean(name = RabbitListenerAnnotationBeanPostProcessor.DEFAULT_RABBIT_LISTENER_CONTAINER_FACTORY_BEAN_NAME)
    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
        ReliableRabbitListenerContainerFactory factory = new ReliableRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }

    @Bean
    public ProcessorInvokerDelegate initProcessorInvokerDelegate() {
        return new SimpleProcessorInvokerDelegate();
    }

}
